//
//  YH_LoginViewController.m
//  YinHang
//
//  Created by 123 on 14-6-18.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_LoginViewController.h"
#import "YH_DisclaimerViewController.h"
#import "YH_HomeViewController.h"

@interface YH_LoginViewController ()
{
    BOOL isRememberPwd;//是否记住密码
    MBProgressHUD *loginHud;
    
    NSArray *userAndPwd;
}
@end

@implementation YH_LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    userAndPwd = [NSArray array];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    [self setUI];
    
    isRememberPwd = YES;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
}
- (void)setUI
{
    UIImage *loginBox_bgImg = [UIImage imageNamed:@"login_loginbox_bg"];
    _loginBox_bgImgView.image = [loginBox_bgImg stretchableImageWithLeftCapWidth:loginBox_bgImg.size.width*0.5f topCapHeight:loginBox_bgImg.size.height*0.5f];
    
    _separateView.backgroundColor = [AOColorFormat colorWithHexString:@"#b4b4b4"];
    _usernameTxtField.textColor = TEXT_COLOR;
    _passwordTxtField.textColor = TEXT_COLOR;
    //记住密码
    NSString *filePath = UPPATH;
    userAndPwd = [NSArray arrayWithContentsOfFile:filePath];
    if ([userAndPwd[0][@"isrember"] isEqualToString:@"0"]) {
        _usernameTxtField.text = @"";
        _passwordTxtField.text = @"";
    }else{
        _usernameTxtField.text = userAndPwd[0][@"user"];
        _passwordTxtField.text = userAndPwd[0][@"password"];
    }
    // 设置文本偏移
    [_usernameTxtField setPadding:YES top:0 right:5 bottom:0 left:5];
    [_passwordTxtField setPadding:YES top:0 right:5 bottom:0 left:5];
    
    UIImage *registerBtn_bgImg = [UIImage imageNamed:@"login_registerbtn"];
    [_registerBtn setBackgroundImage:[registerBtn_bgImg stretchableImageWithLeftCapWidth:registerBtn_bgImg.size.width*0.5f topCapHeight:registerBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    
    UIImage *loginBtn_bgImg = [UIImage imageNamed:@"login_loginbtn"];
    [_loginBtn setBackgroundImage:[loginBtn_bgImg stretchableImageWithLeftCapWidth:loginBtn_bgImg.size.width*0.5f topCapHeight:loginBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    
    
    [_forgetPWBtn setTitleColor:[AOColorFormat colorWithHexString:@"#ffb83c"] forState:UIControlStateNormal];
    _underlineView.backgroundColor = [AOColorFormat colorWithHexString:@"#ffb83c"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    
}

// 输入验证？？？
- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - touchMethod
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [super touchesBegan:touches withEvent:event];
    
    [self allEditActionsResignFirstResponder];
}

#pragma mark - PrivateMethod
- (void)allEditActionsResignFirstResponder{
    [_usernameTxtField resignFirstResponder];
    [_passwordTxtField resignFirstResponder];
}

// 记住密码
- (IBAction)rememberThePasswordBtnClick:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (isRememberPwd == NO) {
        [btn setBackgroundImage:[UIImage imageNamed:@"choosebox_selected"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:@{_usernameTxtField.text: _passwordTxtField.text} forKey:@"userpwd"];
        isRememberPwd = YES;
        
    } else {
        [btn setBackgroundImage:[UIImage imageNamed:@"choosebox"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userpwd"];
        isRememberPwd = NO;
    }
}

// 免费建站
- (IBAction)registerButtonClick:(id)sender {
    
    // 屏幕适配
    YH_DisclaimerViewController *disclaimerVC = [[YH_DisclaimerViewController alloc]initWithNibName:(IPHONE5?@"YH_DisclaimerViewController_4":@"YH_DisclaimerViewController") bundle:nil];
    [self.navigationController pushViewController:disclaimerVC animated:YES];
}

// 快速登录
- (IBAction)loginButtonClick:(id)sender {
    if ([NSString emptyValidate:_usernameTxtField.text] || [NSString emptyValidate:_passwordTxtField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请先填写用户名和密码！"];
        return;
    }
    if (isRememberPwd) {
        //记住密码写进plist
        userAndPwd = @[@{
                           @"user":_usernameTxtField.text,
                           @"password":_passwordTxtField.text,
                           @"isrember":@"1"
                           }];
        NSLog(@"%@",userAndPwd);
        NSString *filePath = UPPATH;
        if ([userAndPwd writeToFile:filePath atomically:YES]) {
            NSLog(@"写入成功");
        }
    }else{
        //记住密码写进plist
        userAndPwd = @[@{@"isrember": @"0"}];
        NSLog(@"%@",userAndPwd);
        NSString *filePath = UPPATH;
        if ([userAndPwd writeToFile:filePath atomically:YES]) {
            NSLog(@"写入成功");
        }
    }
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        loginHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        loginHud.labelText = @"正在登录，请稍后...";
        
        ASIFormDataRequest *loginRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        loginRequest.requestMethod = @"POST";
        // 设置超时时间
        loginRequest.timeOutSeconds = 15;
        loginRequest.delegate = self;
        // 设置参数
        NSDictionary *paramsDict = @{@"username": _usernameTxtField.text, @"userpwd": [_passwordTxtField.text md5]};
        //NSDictionary *paramsDict = @{@"username": @"互联天下", @"userpwd": [@"123456" md5]};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        //NSString *templateParamStr = @"{\"action\":\"%@\",\"params\":%@}";
        //NSString *result = [NSString stringWithFormat:templateParamStr,@"login",paramsStr];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"login",paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        loginRequest.postBody = [paramsData mutableCopy];
        //NSLog(@"%@",[[NSString alloc]initWithData:loginRequest.postBody encoding:ENCODING_FOR_GB]);
        
        [loginRequest startAsynchronous];
    }
    
    
    
//    YH_HomeViewController *homeVC = [[YH_HomeViewController alloc]initWithNibName:@"YH_HomeViewController" bundle:nil];
//    [self.navigationController pushViewController:homeVC animated:YES];
}

// 忘记密码
- (IBAction)forgetPassword:(id)sender {
}



#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    NSString * responseString = [request responseString];
    responseString = [responseString stringByReplacingOccurrencesOfString:@"nnnn11" withString:@""];
    
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            [loginHud hide:YES];
            
            // 登陆成功 进入主页...
            
            NSDictionary *info = result[@"info"];
            NSString *username = info[@"username"];
            NSString *userId = info[@"cid"];
            NSString *phoneUrl = info[@"phonurllink"];
            
            // 保存用户名和用户id
            [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
            //保存预览URL
            [[NSUserDefaults standardUserDefaults] setObject:phoneUrl forKey:@"phoneUrl"];
            
            //保存密码 用于修改
            [[NSUserDefaults standardUserDefaults] setObject:_passwordTxtField.text forKey:@"userpwd"];
            //NSLog(@"%@",UPWD_OLD);
            YH_HomeViewController *homeVC = [[YH_HomeViewController alloc]initWithNibName:@"YH_HomeViewController" bundle:nil];
            [self.navigationController pushViewController:homeVC animated:YES];
            
            
        } else {
            [loginHud hide:YES];
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
        
    } else {
        [loginHud hide:YES];
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [loginHud hide:YES];
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

@end
